const http = require("http");
const fs = require("fs");
const url = require("url");
const querystring = require("querystring");
const uuid=require("node-uuid");

http.createServer((req,res)=>{
    if(req.url !== "/favicon.ico"){
        const urlObj = url.parse(req.url,true);
        switch(urlObj.pathname){
            case "/api":
                ajaxHandle(req,res);
                break;
            default:
                fileHandle(req,res);
        }
    }
}).listen("81","127.0.0.1",function(){
    console.log("欢迎欢迎")
})

function ajaxHandle(req,res){
    let data = "";
    req.on("data",(s)=>{
        data += s;
    })
    req.on("end",()=>{
        if(data === ""){
            const urlObj = url.parse(req.url,true);
            data = urlObj.query;
        }else{
            data = querystring.parse(data)
        }

        switch(data.type){
            case "login":
                login(data,req,res);
                break;
            case "register":
                register(data,req,res);
                break;
        }
    })
}

let userMsg = [];

function login(data,req,res){
    let i;
    const onoff = userMsg.some((val,idx)=>{
        i = idx;
        return val.user === data.user;
    })

    let msg = {};

    if(onoff){
        if(userMsg[i].pass === data.pass){
            userMsg[i].state = 1;
            msg = {code:200,msg:"登录成功",data:userMsg[i]};
        }else{
            msg = {code:400,msg:"用户名密码不匹配",data:"NOT DATA"}
        }
    }else{
        msg = {code:404,msg:"用户名不存在，需要注册",data:"NOT DATA"}
    }
    res.write(JSON.stringify(msg));
    res.end();
}

function register(data,req,res){
    let i;
    const onoff = userMsg.some((val,idx)=>{
        i = idx;
        return val.user === data.user;
    })

    let msg = {};
    if(onoff){
        msg = {code:1,msg:"用户名重复",data:"NOT DATA"};
    }else{
        const v1Str = uuid.v1();
        // 没有重复，再进行注册
        userMsg.push({
            userId:v1Str,
            user:data.user,
            pass:data.pass,
            state:0
        })
        msg = {
            code:200,
            msg:"注册成功",
            data:{
                userId:v1Str,
                user:data.user,
                pass:data.pass,
                state:0
            }
        };
    }
    res.write(JSON.stringify(msg));
    res.end();
}




function fileHandle(req,res){
    const urlObj = url.parse(req.url);
    const path = "./www" + urlObj.pathname;

    fs.readFile(path,(err,data)=>{
        if(!err){
            res.write(data);
        }else{
            res.write("404");
        }
        res.end();
    })
}